[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This chapter describes the GNU C library’s functions for manipulating files. Unlike the input and output functions described in @ref{I/O on Streams} and @ref{Low-Level I/O}, these functions are concerned with operating on the files themselves, rather than on their contents.
Among the facilities described in this chapter are functions for examining or modifying directories, functions for renaming and deleting files, and functions for examining and setting file attributes such as access permissions and modification times.
1.1 Working Directory | This is used to resolve relative file names. | |
1.2 Accessing Directories | Finding out what files a directory contains. | |
1.3 Hard Links | Adding alternate names to a file. | |
1.4 Symbolic Links | A file that “points to” a file name. | |
1.5 Deleting Files | How to delete a file, and what that means. | |
1.6 Renaming Files | Changing a file’s name. | |
1.7 Creating Directories | A system call just for creating a directory. | |
1.8 File Attributes | Attributes of individual files. | |
1.9 Making Special Files | How to create special files. | |
1.10 Temporary Files | Naming and creating temporary files. |
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Each process has associated with it a directory, called its current working directory or simply working directory, that is used in the resolution of relative file names (@pxref{File Name Resolution}).
When you log in and begin a new session, your working directory is
initially set to the home directory associated with your login account
in the system user database. You can find any user’s home directory
using the getpwuid
or getpwnam
functions; see @ref{User
Database}.
Users can change the working directory using shell commands like
cd
. The functions described in this section are the primitives
used by those commands and by other programs for examining and changing
the working directory.
Prototypes for these functions are declared in the header file ‘unistd.h’.
The getcwd
function returns an absolute file name representing
the current working directory, storing it in the character array
buffer that you provide. The size argument is how you tell
the system the allocation size of buffer.
The GNU library version of this function also permits you to specify a
null pointer for the buffer argument. Then getcwd
allocates a buffer automatically, as with malloc
(@pxref{Unconstrained Allocation}). If the size is greater than
zero, then the buffer is that large; otherwise, the buffer is as large
as necessary to hold the result.
The return value is buffer on success and a null pointer on failure.
The following errno
error conditions are defined for this function:
EINVAL
The size argument is zero and buffer is not a null pointer.
ERANGE
The size argument is less than the length of the working directory name. You need to allocate a bigger array and try again.
EACCES
Permission to read or search a component of the file name was denied.
Here is an example showing how you could implement the behavior of GNU’s
getcwd (NULL, 0)
using only the standard behavior of
getcwd
:
char * gnu_getcwd () { int size = 100; char *buffer = (char *) xmalloc (size); while (1) { char *value = getcwd (buffer, size); if (value != 0) return buffer; size *= 2; free (buffer); buffer = (char *) xmalloc (size); } }
@xref{Malloc Examples}, for information about xmalloc
, which is
not a library function but is a customary name used in most GNU
software.
This is similar to getcwd
. The GNU library provides getwd
for backwards compatibility with BSD. The buffer should be a
pointer to an array at least PATH_MAX
bytes long.
This function is used to set the process’s working directory to filename.
The normal, successful return value from chdir
is 0
. A
value of -1
is returned to indicate an error. The errno
error conditions defined for this function are the usual file name
syntax errors (@pxref{File Name Errors}), plus ENOTDIR
if the
file filename is not a directory.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The facilities described in this section let you read the contents of a directory file. This is useful if you want your program to list all the files in a directory, perhaps as part of a menu.
The opendir
function opens a directory stream whose
elements are directory entries. You use the readdir
function on
the directory stream to retrieve these entries, represented as
struct dirent
objects. The name of the file for each entry is
stored in the d_name
member of this structure. There are obvious
parallels here to the stream facilities for ordinary files, described in
@ref{I/O on Streams}.
1.2.1 Format of a Directory Entry | Format of one directory entry. | |
1.2.2 Opening a Directory Stream | How to open a directory stream. | |
1.2.3 Reading and Closing a Directory Stream | How to read directory entries from the stream. | |
1.2.4 Simple Program to List a Directory | A very simple directory listing program. | |
1.2.5 Random Access in a Directory Stream | Rereading part of the directory already read with the same stream. |
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section describes what you find in a single directory entry, as you might obtain it from a directory stream. All the symbols are declared in the header file ‘dirent.h’.
This is a structure type used to return information about directory entries. It contains the following fields:
char *d_name
This is the null-terminated file name component. This is the only field you can count on in all POSIX systems.
ino_t d_fileno
This is the file serial number. For BSD compatibility, you can also
refer to this member as d_ino
.
size_t d_namlen
This is the length of the file name, not including the terminating null character.
This structure may contain additional members in the future.
When a file has multiple names, each name has its own directory entry.
The only way you can tell that the directory entries belong to a
single file is that they have the same value for the d_fileno
field.
File attributes such as size, modification times, and the like are part of the file itself, not any particular directory entry. See section File Attributes.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section describes how to open a directory stream. All the symbols are declared in the header file ‘dirent.h’.
The DIR
data type represents a directory stream.
You shouldn’t ever allocate objects of the struct dirent
or
DIR
data types, since the directory access functions do that for
you. Instead, you refer to these objects using the pointers returned by
the following functions.
The opendir
function opens and returns a directory stream for
reading the directory whose file name is dirname. The stream has
type DIR *
.
If unsuccessful, opendir
returns a null pointer. In addition to
the usual file name syntax errors (@pxref{File Name Errors}), the
following errno
error conditions are defined for this function:
EACCES
Read permission is denied for the directory named by dirname
.
EMFILE
The process has too many files open.
ENFILE
The entire system, or perhaps the file system which contains the directory, cannot support any additional open files at the moment. (This problem cannot happen on the GNU system.)
The DIR
type is typically implemented using a file descriptor,
and the opendir
function in terms of the open
function.
@xref{Low-Level I/O}. Directory streams and the underlying
file descriptors are closed on exec
(@pxref{Executing a File}).
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section describes how to read directory entries from a directory stream, and how to close the stream when you are done with it. All the symbols are declared in the header file ‘dirent.h’.
This function reads the next entry from the directory. It normally returns a pointer to a structure containing information about the file. This structure is statically allocated and can be rewritten by a subsequent call.
Portability Note: On some systems, readdir
may not
return entries for ‘.’ and ‘..’, even though these are always
valid file names in any directory. @xref{File Name Resolution}.
If there are no more entries in the directory or an error is detected,
readdir
returns a null pointer. The following errno
error
conditions are defined for this function:
EBADF
The dirstream argument is not valid.
This function closes the directory stream dirstream. It returns
0
on success and -1
on failure.
The following errno
error conditions are defined for this
function:
EBADF
The dirstream argument is not valid.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Here’s a simple program that prints the names of the files in the current working directory:
The order in which files appear in a directory tends to be fairly random. A more useful program would sort the entries (perhaps by alphabetizing them) before printing them; see @ref{Array Sort Function}.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section describes how to reread parts of a directory that you have already read from an open directory stream. All the symbols are declared in the header file ‘dirent.h’.
The rewinddir
function is used to reinitialize the directory
stream dirstream, so that if you call readdir
it
returns information about the first entry in the directory again. This
function also notices if files have been added or removed to the
directory since it was opened with opendir
. (Entries for these
files might or might not be returned by readdir
if they were
added or removed since you last called opendir
or
rewinddir
.)
The telldir
function returns the file position of the directory
stream dirstream. You can use this value with seekdir
to
restore the directory stream to that position.
The seekdir
function sets the file position of the directory
stream dirstream to pos. The value pos must be the
result of a previous call to telldir
on this particular stream;
closing and reopening the directory can invalidate values returned by
telldir
.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In POSIX systems, one file can have many names at the same time. All of the names are equally real, and no one of them is preferred to the others.
To add a name to a file, use the link
function. (The new name is
also called a hard link to the file.) Creating a new link to a
file does not copy the contents of the file; it simply makes a new name
by which the file can be known, in addition to the file’s existing name
or names.
One file can have names in several directories, so the the organization of the file system is not a strict hierarchy or tree.
Since a particular file exists within a single file system, all its
names must be in directories in that file system. link
reports
an error if you try to make a hard link to the file from another file
system.
The prototype for the link
function is declared in the header
file ‘unistd.h’.
The link
function makes a new link to the existing file named by
oldname, under the new name newname.
This function returns a value of 0
if it is successful and
-1
on failure. In addition to the usual file name syntax errors
(@pxref{File Name Errors}) for both oldname and newname, the
following errno
error conditions are defined for this function:
EACCES
The directory in which the new link is to be written is not writable.
EEXIST
There is already a file named newname. If you want to replace this link with a new link, you must remove the old link explicitly first.
EMLINK
There are already too many links to the file named by oldname.
(The maximum number of links to a file is LINK_MAX
; see
@ref{Limits for Files}.)
Well-designed file systems never report this error, because they permit more links than your disk could possibly hold. However, you must still take account of the possibility of this error, as it could result from network access to a file system on another machine.
ENOENT
The file named by oldname doesn’t exist. You can’t make a link to a file that doesn’t exist.
ENOSPC
The directory or file system that would contain the new link is “full” and cannot be extended.
EPERM
Some implementations only allow privileged users to make links to directories, and others prohibit this operation entirely. This error is used to report the problem.
EROFS
The directory containing the new link can’t be modified because it’s on a read-only file system.
EXDEV
The directory specified in newname is on a different file system than the existing file.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The GNU system supports soft links or symbolic links. This is a kind of “file” that is essentially a pointer to another file name. Unlike hard links, symbolic links can be made to directories or across file systems with no restrictions. You can also make a symbolic link to a name which is not the name of any file. (Opening this link will fail until a file by that name is created.) Likewise, if the symbolic link points to an existing file which is later deleted, the symbolic link continues to point to the same file name even though the name no longer names any file.
The reason symbolic links work the way they do is that special things
happen when you try to open the link. The open
function realizes
you have specified the name of a link, reads the file name contained in
the link, and opens that file name instead. The stat
function
likewise operates on the file that the symbolic link points to, instead
of on the link itself. So does link
, the function that makes a
hard link.
By contrast, other operations such as deleting or renaming the file
operate on the link itself. The functions readlink
and
lstat
also refrain from following symbolic links, because
their purpose is to obtain information about the link.
Prototypes for the functions listed in this section are in ‘unistd.h’.
The symlink
function makes a symbolic link to oldname named
newname.
The normal return value from symlink
is 0
. A return value
of -1
indicates an error. In addition to the usual file name
syntax errors (@pxref{File Name Errors}), the following errno
error conditions are defined for this function:
EEXIST
There is already an existing file named newname.
EROFS
The file newname would exist on a read-only file system.
ENOSPC
The directory or file system cannot be extended to make the new link.
EIO
A hardware error occurred while reading or writing data on the disk.
The readlink
function gets the value of the symbolic link
filename. The file name that the link points to is copied into
buffer. This file name string is not null-terminated;
readlink
normally returns the number of characters copied. The
size argument specifies the maximum number of characters to copy,
usually the allocation size of buffer.
If the return value equals size, you cannot tell whether or not
there was room to return the entire name. So make a bigger buffer and
call readlink
again. Here is an example:
char * readlink_malloc (char *filename) { int size = 100; while (1) { char *buffer = (char *) xmalloc (size); int nchars = readlink (filename, buffer, size); if (nchars < size) return buffer; free (buffer); size *= 2; } }
A value of -1
is returned in case of error. In addition to the
usual file name syntax errors (@pxref{File Name Errors}), the following
errno
error conditions are defined for this function:
EINVAL
The named file is not a symbolic link.
EIO
A hardware error occurred while reading or writing data on the disk.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can delete a file with the functions unlink
or remove
.
(These names are synonymous.)
Deletion actually deletes a file name. If this is the file’s only name, then the file is deleted as well. If the file has other names as well (see section Hard Links), it remains accessible under its other names.
The unlink
function deletes the file name filename. If
this is a file’s sole name, the file itself is also deleted. (Actually,
if any process has the file open when this happens, deletion is
postponed until all processes have closed the file.)
The function unlink
is declared in the header file ‘unistd.h’.
This function returns 0
on successful completion, and -1
on error. In addition to the usual file name syntax errors
(@pxref{File Name Errors}), the following errno
error conditions are
defined for this function:
EACCESS
Write permission is denied for the directory from which the file is to be removed.
EBUSY
This error indicates that the file is being used by the system in such a way that it can’t be unlinked. Examples of situations where you might see this error are if the file name specifies the root directory or a mount point for a file system.
ENOENT
The file name to be deleted doesn’t exist.
EPERM
On some systems, unlink
cannot be used to delete the name of a
directory, or can only be used this way by a privileged user.
To avoid such problems, use rmdir
to delete directories.
EROFS
The directory in which the file name is to be deleted is on a read-only file system, and can’t be modified.
The remove
function is another name for unlink
.
remove
is the ANSI C name, whereas unlink
is the POSIX.1
name. The name remove
is declared in ‘stdio.h’.
The rmdir
function deletes a directory. The directory must be
empty before it can be removed; in other words, it can only contain
entries for ‘.’ and ‘..’.
In most other respects, rmdir
behaves like unlink
. There
are two additional errno
error conditions defined for
rmdir
:
EEXIST
ENOTEMPTY
The directory to be deleted is not empty.
These two error codes are synonymous; some systems use one, and some use the other.
The prototype for this function is declared in the header file ‘unistd.h’.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The rename
function is used to change a file’s name.
The rename
function renames the file name oldname with
newname. The file formerly accessible under the name
oldname is afterward accessible as newname instead. (If the
file had any other names aside from oldname, it continues to have
those names.)
The directory containing the name newname must be on the same file system as the file (as indicated by the name oldname).
One special case for rename
is when oldname and
newname are two names for the same file. The consistent way to
handle this case is to delete oldname. However, POSIX says that
in this case rename
does nothing and reports success—which is
inconsistent. We don’t know what your operating system will do. The
GNU system, when completed, will probably do the right thing (delete
oldname) unless you explicitly request strict POSIX compatibility
“even when it hurts”.
If the oldname is not a directory, then any existing file named
newname is removed during the renaming operation. However, if
newname is the name of a directory, rename
fails in this
case.
If the oldname is a directory, then either newname must not
exist or it must name a directory that is empty. In the latter case,
the existing directory named newname is deleted first. The name
newname must not specify a subdirectory of the directory
oldname
which is being renamed.
One useful feature of rename
is that the meaning of the name
newname changes “atomically” from any previously existing file
by that name to its new meaning (the file that was called
oldname). There is no instant at which newname is
nonexistent “in between” the old meaning and the new meaning.
If rename
fails, it returns -1
. In addition to the usual
file name syntax errors (@pxref{File Name Errors}), the following
errno
error conditions are defined for this function:
EACCES
One of the directories containing newname or oldname refuses write permission; or newname and oldname are directories and write permission is refused for one of them.
EBUSY
A directory named by oldname or newname is being used by the system in a way that prevents the renaming from working. This includes directories that are mount points for filesystems, and directories that are the current working directories of processes.
EEXIST
The directory newname isn’t empty.
ENOTEMPTY
The directory newname isn’t empty.
EINVAL
The oldname is a directory that contains newname.
EISDIR
The newname names a directory, but the oldname doesn’t.
EMLINK
The parent directory of newname would have too many links.
Well-designed file systems never report this error, because they permit more links than your disk could possibly hold. However, you must still take account of the possibility of this error, as it could result from network access to a file system on another machine.
ENOENT
The file named by oldname doesn’t exist.
ENOSPC
The directory that would contain newname has no room for another entry, and there is no space left in the file system to expand it.
EROFS
The operation would involve writing to a directory on a read-only file system.
EXDEV
The two file names newname and oldnames are on different file systems.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Directories are created with the mkdir
function. (There is also
a shell command mkdir
which does the same thing.)
The mkdir
function creates a new, empty directory whose name is
filename.
The argument mode specifies the file permissions for the new directory file. See section The Mode Bits for Access Permission, for more information about this.
A return value of 0
indicates successful completion, and
-1
indicates failure. In addition to the usual file name syntax
errors (@pxref{File Name Errors}), the following errno
error
conditions are defined for this function:
EACCES
Write permission is denied for the parent directory in which the new directory is to be added.
EEXIST
A file named filename already exists.
EMLINK
The parent directory has too many links.
Well-designed file systems never report this error, because they permit more links than your disk could possibly hold. However, you must still take account of the possibility of this error, as it could result from network access to a file system on another machine.
ENOSPC
The file system doesn’t have enough room to create the new directory.
EROFS
The parent directory of the directory being created is on a read-only file system, and cannot be modified.
To use this function, your program should include the header file ‘sys/stat.h’.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
When you issue an ‘ls -l’ shell command on a file, it gives you information about the size of the file, who owns it, when it was last modified, and the like. This kind of information is called the file attributes; it is associated with the file itself and not a particular one of its names.
This section contains information about how you can inquire about and modify these attributes of files.
1.8.1 What the File Attribute Values Mean | The names of the file attributes, and what their values mean. | |
1.8.2 Reading the Attributes of a File | How to read the attributes of a file. | |
1.8.3 Testing the Type of a File | Distinguishing ordinary files, directories, links... | |
1.8.4 File Owner | How ownership for new files is determined, and how to change it. | |
1.8.5 The Mode Bits for Access Permission | How information about a file’s access mode is stored. | |
1.8.6 How Your Access to a File is Decided | How the system decides who can access a file. | |
1.8.7 Assigning File Permissions | How permissions for new files are assigned, and how to change them. | |
1.8.8 Testing Permission to Access a File | How to find out if your process can access a file. | |
1.8.9 File Times | About the time attributes of a file. |
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
When you read the attributes of a file, they come back in a structure
called struct stat
. This section describes the names of the
attributes, their data types, and what they mean. For the functions
to read the attributes of a file, see Reading the Attributes of a File.
The header file ‘sys/stat.h’ declares all the symbols defined in this section.
The stat
structure type is used to return information about the
attributes of a file. It contains at least the following members:
mode_t st_mode
Specifies the mode of the file. This includes file type information (see section Testing the Type of a File) and the file permission bits (see section The Mode Bits for Access Permission).
ino_t st_ino
The file serial number, which distinguishes this file from all other files on the same device.
dev_t st_dev
Identifies the device containing the file. The st_ino
and
st_dev
, taken together, uniquely identify the file.
nlink_t st_nlink
The number of hard links to the file. This count keeps track of how many directories have entries for this file. If the count is ever decremented to zero, then the file itself is discarded. Symbolic links are not counted in the total.
uid_t st_uid
The user ID of the file’s owner. See section File Owner.
gid_t st_gid
The group ID of the file. See section File Owner.
off_t st_size
This specifies the size of a regular file in bytes. For files that are really devices and the like, this field isn’t usually meaningful.
time_t st_atime
This is the last access time for the file. See section File Times.
unsigned long int st_atime_usec
This is the fractional part of the last access time for the file. See section File Times.
time_t st_mtime
This is the time of the last modification to the contents of the file. See section File Times.
unsigned long int st_mtime_usec
This is the fractional part of the time of last modification to the contents of the file. See section File Times.
time_t st_ctime
This is the time of the last modification to the attributes of the file. See section File Times.
unsigned long int st_ctime_usec
This is the fractional part of the time of last modification to the attributes of the file. See section File Times.
unsigned int st_nblocks
This is the amount of disk space that the file occupies, measured in units of 512-byte blocks.
The number of disk blocks is not strictly proportional to the size of the file, for two reasons: the file system may use some blocks for internal record keeping; and the file may be sparse—it may have “holes” which contain zeros but do not actually take up space on the disk.
You can tell (approximately) whether a file is sparse by comparing this
value with st_size
, like this:
(st.st_blocks * 512 < st.st_size)
This test is not perfect because a file that is just slightly sparse might not be detected as sparse at all. For practical applications, this is not a problem.
unsigned int st_blksize
The optimal block size for reading of writing this file. You might use this size for allocating the buffer space for reading of writing the file.
Some of the file attributes have special data type names which exist specifically for those attributes. (They are all aliases for well-known integer types that you know and love.) These typedef names are defined in the header file ‘sys/types.h’ as well as in ‘sys/stat.h’. Here is a list of them.
This is an integer data type used to represent file modes. In the
GNU system, this is equivalent to unsigned int
.
This is an arithmetic data type used to represent file serial numbers.
(In Unix jargon, these are sometimes called inode numbers.)
In the GNU system, this type is equivalent to unsigned long int
.
This is an arithmetic data type used to represent file device numbers.
In the GNU system, this is equivalent to int
.
This is an arithmetic data type used to represent file link counts.
In the GNU system, this is equivalent to unsigned short int
.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
To examine the attributes of files, use the functions stat
,
fstat
and lstat
. They return the attribute information in
a struct stat
object. All three functions are declared in the
header file ‘sys/stat.h’.
The stat
function returns information about the attributes of the
file named by filename in the structure pointed at by buf.
If filename is the name of a symbolic link, the attributes you get
describe the file that the link points to. If the link points to a
nonexistent file name, then stat
fails, reporting a nonexistent
file.
The return value is 0
if the operation is successful, and -1
on failure. In addition to the usual file name syntax errors
(@pxref{File Name Errors}, the following errno
error conditions
are defined for this function:
ENOENT
The file named by filename doesn’t exist.
The fstat
function is like stat
, except that it takes an
open file descriptor as an argument instead of a file name.
@xref{Low-Level I/O}.
Like stat
, fstat
returns 0
on success and -1
on failure. The following errno
error conditions are defined for
fstat
:
EBADF
The filedes argument is not a valid file descriptor.
The lstat
function is like stat
, except that it does not
follow symbolic links. If filename is the name of a symbolic
link, lstat
returns information about the link itself; otherwise,
lstat
works like stat
. See section Symbolic Links.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The file mode, stored in the st_mode
field of the file
attributes, contains two kinds of information: the file type code, and
the access permission bits. This section discusses only the type code,
which you can use to tell whether the file is a directory, whether it is
a socket, and so on. For information about the access permission,
The Mode Bits for Access Permission.
There are two predefined ways you can access the file type portion of the file mode. First of all, for each type of file, there is a predicate macro which examines a file mode value and returns true or false—is the file of that type, or not. Secondly, you can mask out the rest of the file mode to get just a file type code. You can compare this against various constants for the supported file types.
All of the symbols listed in this section are defined in the header file ‘sys/stat.h’.
The following predicate macros test the type of a file, given the value
m which is the st_mode
field returned by stat
on
that file:
This macro returns nonzero if the file is a directory.
This macro returns nonzero if the file is a character special file (a device like a terminal).
This macro returns nonzero if the file is a block special file (a device like a disk).
This macro returns nonzero if the file is a regular file.
This macro returns nonzero if the file is a FIFO special file, or a pipe. @xref{Pipes and FIFOs}.
This macro returns nonzero if the file is a symbolic link. See section Symbolic Links.
This macro returns nonzero if the file is a socket. @xref{Sockets}.
An alterate non-POSIX method of testing the file type is supported for
compatibility with BSD. The mode can be bitwise ANDed with
S_IFMT
to extract the file type code, and compared to the
appropriate type code constant. For example,
S_ISCHR (mode)
is equivalent to:
((mode & S_IFMT) == S_IFCHR)
This is a bit mask used to extract the file type code portion of a mode value.
These are the symbolic names for the different file type codes:
S_IFDIR
This macro represents the value of the file type code for a directory file.
S_IFCHR
This macro represents the value of the file type code for a character-oriented device file.
S_IFBLK
This macro represents the value of the file type code for a block-oriented device file.
S_IFREG
This macro represents the value of the file type code for a regular file.
S_IFLNK
This macro represents the value of the file type code for a symbolic link.
S_IFSOCK
This macro represents the value of the file type code for a socket.
S_IFIFO
This macro represents the value of the file type code for a FIFO or pipe.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Every file has an owner which is one of the registered user names defined on the system. Each file also has a group, which is one of the defined groups. The file owner can often be useful for showing you who edited the file (especially when you edit with GNU Emacs), but its main purpose is for access control.
The file owner and group play a role in determining access because the file has one set of access permission bits for the user that is the owner, another set that apply to users who belong to the file’s group, and a third set of bits that apply to everyone else. See section How Your Access to a File is Decided, for the details of how access is decided based on this data.
When a file is created, its owner is set from the effective user ID of the process that creates it (@pxref{Process Persona}). The file’s group ID may be set from either effective group ID of the process, or the group ID of the directory that contains the file, depending on the system where the file is stored. When you access a remote file system, it behaves according to its own rule, not according to the system your program is running on. Thus, your program must be prepared to encounter either kind of behavior, no matter what kind of system you run it on.
You can change the owner and/or group owner of an existing file using
the chown
function. This is the primitive for the chown
and chgrp
shell commands.
The prototype for this function is declared in ‘unistd.h’.
The chown
function changes the owner of the file filename to
owner, and its group owner to group.
Changing the owner of the file on certain systems clears the set-user-ID and set-group-ID bits of the file’s permissions. (This is because those bits may not be appropriate for the new owner.) The other file permission bits are not changed.
The return value is 0
on success and -1
on failure.
In addition to the usual file name syntax errors (@pxref{File Name Errors}),
the following errno
error conditions are defined for this function:
EPERM
This process lacks permission to make the requested change.
Only privileged users or the file’s owner can change the file’s group. On most file systems, only privileged users can change the file owner; some file systems allow you to change the owner if you are currently the owner. When you access a remote file system, the behavior you encounter is determined by the system that actually holds the file, not by the system your program is running on.
@xref{Options for Files}, for information about the
_POSIX_CHOWN_RESTRICTED
macro.
EROFS
The file is on a read-only file system.
This is like chown
, except that it changes the owner of the file
with open file descriptor filedes.
The return value from fchown
is 0
on success and -1
on failure. The following errno
error codes are defined for this
function:
EBADF
The filedes argument is not a valid file descriptor.
EINVAL
The filedes argument corresponds to a pipe or socket, not an ordinary file.
EPERM
This process lacks permission to make the requested change. For
details, see chmod
, above.
EROFS
The file resides on a read-only file system.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The file mode, stored in the st_mode
field of the file
attributes, contains two kinds of information: the file type code, and
the access permission bits. This section discusses only the access
permission bits, which control who can read or write the file.
See section Testing the Type of a File, for information about the file type code.
All of the symbols listed in this section are defined in the header file ‘sys/stat.h’.
These symbolic constants are defined for the file mode bits that control access permission for the file:
S_IRUSR
S_IREAD
Read permission bit for the owner of the file. On many systems, this
bit is 0400. S_IREAD
is an obsolete synonym provided for BSD
compatibility.
S_IWUSR
S_IWRITE
Write permission bit for the owner of the file. Usually 0200.
S_IWRITE
is an obsolete synonym provided for BSD compatibility.
S_IXUSR
S_IEXEC
Execute (for ordinary files) or search (for directories) permission bit
for the owner of the file. Usually 0100. S_IEXEC
is an obsolete
synonym provided for BSD compatibility.
S_IRWXU
This is equivalent to ‘(S_IRUSR | S_IWUSR | S_IXUSR)’.
S_IRGRP
Read permission bit for the group owner of the file. Usually 040.
S_IWGRP
Write permission bit for the group owner of the file. Usually 020.
S_IXGRP
Execute or search permission bit for the group owner of the file. Usually 010.
S_IRWXG
This is equivalent to ‘(S_IRGRP | S_IWGRP | S_IXGRP)’.
S_IROTH
Read permission bit for other users. Usually 04.
S_IWOTH
Write permission bit for other users. Usually 02.
S_IXOTH
Execute or search permission bit for other users. Usually 01.
S_IRWXO
This is equivalent to ‘(S_IROTH | S_IWOTH | S_IXOTH)’.
S_ISUID
This is the set-user-ID on execute bit, usually 04000. @xref{How Change Persona}.
S_ISGID
This is the set-group-ID on execute bit, usually 02000. @xref{How Change Persona}.
S_ISVTX
This is the sticky bit, usually 01000.
On an executable file, it modifies the swapping policies of the system. Normally, when a program terminates, its pages in core are immediately freed and reused. If the sticky bit is set on the executable file, the system keeps the pages in core for a while as if the program were still running. This is advantageous for a program that is likely to be run many times in succession.
On a directory, the sticky bit gives permission to delete a file in the directory if you can write the contents of that file. Ordinarily, a user either can delete all the files in the directory or cannot delete any of them (based on whether the user has write permission for the directory). The sticky bit makes it possible to control deletion for individual files.
The actual bit values of the symbols are listed in the table above so you can decode file mode values when debugging your programs. These bit values are correct for most systems, but they are not guaranteed.
Warning: Writing explicit numbers for file permissions is bad practice. It is not only nonportable, it also requires everyone who reads your program to remember what the bits mean. To make your program clean, use the symbolic names.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Recall that the operating system normally decides access permission for a file based on the effective user and group IDs of the process, and its supplementary group IDs, together with the file’s owner, group and permission bits. These concepts are discussed in detail in @ref{Process Persona}.
If the effective user ID of the process matches the owner user ID of the file, then permissions for read, write, and execute/search are controlled by the corresponding “user” (or “owner”) bits. Likewise, if any of the effective group ID or supplementary group IDs of the process matches the group owner ID of the file, then permissions are controlled by the “group” bits. Otherwise, permissions are controlled by the “other” bits.
Privileged users, like ‘root’, can access any file, regardless of its file permission bits. As a special case, for a file to be executable even for a privileged user, at least one of its execute bits must be set.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The primitive functions for creating files (for example, open
or
mkdir
) take a mode argument, which specifies the file
permissions for the newly created file. But the specified mode is
modified by the process’s file creation mask, or umask,
before it is used.
The bits that are set in the file creation mask identify permissions that are always to be disabled for newly created files. For example, if you set all the “other” access bits in the mask, then newly created files are not accessible at all to processes in the “other” category, even if the mode argument specified to the creation function would permit such access. In other words, the file creation mask is the complement of the ordinary access permissions you want to grant.
Programs that create files typically specify a mode argument that includes all the permissions that make sense for the particular file. For an ordinary file, this is typically read and write permission for all classes of users. These permissions are then restricted as specified by the individual user’s own file creation mask.
To change the permission of an existing file given its name, call
chmod
. This function ignores the file creation mask; it uses
exactly the specified permission bits.
In normal use, the file creation mask is initialized in the user’s login
shell (using the umask
shell command), and inherited by all
subprocesses. Application programs normally don’t need to worry about
the file creation mask. It will do automatically what it is supposed to
do.
When your program should create a file and bypass the umask for its
access permissions, the easiest way to do this is to use fchmod
after opening the file, rather than changing the umask.
In fact, changing the umask is usually done only by shells. They use
the umask
function.
The functions in this section are declared in ‘sys/stat.h’.
The umask
function sets the file creation mask of the current
process to mask, and returns the previous value of the file
creation mask.
Here is an example showing how to read the mask with umask
without changing it permanently:
mode_t read_umask (void) { mask = umask (0); umask (mask); }
However, it is better to use getumask
if you just want to read
the mask value, because that is reentrant (at least if you use the GNU
operating system).
Return the current value of the file creation mask for the current process. This function is a GNU extension.
The chmod
function sets the access permission bits for the file
named by filename to mode.
If the filename names a symbolic link, chmod
changes the
permission of the file pointed to by the link, not those of the link
itself. There is actually no way to set the mode of a link, which is
always -1
.
This function returns 0
if successful and -1
if not. In
addition to the usual file name syntax errors (@pxref{File Name
Errors}), the following errno
error conditions are defined for
this function:
ENOENT
The named file doesn’t exist.
EPERM
This process does not have permission to change the access permission of this file. Only the file’s owner (as judged by the effective user ID of the process) or a privileged user can change them.
EROFS
The file resides on a read-only file system.
This is like chmod
, except that it changes the permissions of
the file currently open via descriptor filedes.
The return value from fchmod
is 0
on success and -1
on failure. The following errno
error codes are defined for this
function:
EBADF
The filedes argument is not a valid file descriptor.
EINVAL
The filedes argument corresponds to a pipe or socket, or something else that doesn’t really have access permissions.
EPERM
This process does not have permission to change the access permission of this file. Only the file’s owner (as judged by the effective user ID of the process) or a privileged user can change them.
EROFS
The file resides on a read-only file system.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
When a program runs as a privileged user, this permits it to access
files off-limits to ordinary users—for example, to modify
‘/etc/passwd’. Programs designed to be run by ordinary users but
access such files use the setuid bit feature so that they always run
with root
as the effective user ID.
Such a program may also access files specified by the user, files which
conceptually are being accessed explicitly by the user. Since the
program runs as root
, it has permission to access whatever file
the user specifies—but usually the desired behavior is to permit only
those files which the user could ordinarily access.
The program therefore must explicitly check whether the user would have the necessary access to a file, before it reads or writes the file.
To do this, use the function access
, which checks for access
permission based on the process’s real user ID rather than the
effective user ID. (The setuid feature does not alter the real user ID,
so it reflects the user who actually ran the program.)
There is another way you could check this access, which is easy to
describe, but very hard to use. This is to examine the file mode bits
and mimic the system’s own access computation. This method is
undesirable because many systems have additional access control
features; your program cannot portably mimic them, and you would not
want to try to keep track of the diverse features that different systems
have. Using access
is simple and automatically does whatever is
appropriate for the system you are using.
The symbols in this section are declared in ‘unistd.h’.
The access
function checks to see whether the file named by
filename can be accessed in the way specified by the how
argument. The how argument either can be the bitwise OR of the
flags R_OK
, W_OK
, X_OK
, or the existence test
F_OK
.
This function uses the real user and group ID’s of the calling
process, rather than the effective ID’s, to check for access
permission. As a result, if you use the function from a setuid
or setgid
program (@pxref{How Change Persona}), it gives
information relative to the user who actually ran the program.
The return value is 0
if the access is permitted, and -1
otherwise. (In other words, treated as a predicate function,
access
returns true if the requested access is denied.)
In addition to the usual file name syntax errors (@pxref{File Name
Errors}), the following errno
error conditions are defined for
this function:
EACCES
The access specified by how is denied.
ENOENT
The file doesn’t exist.
EROFS
Write permission was requested for a file on a read-only file system.
These macros are defined in the header file ‘unistd.h’ for use
as the how argument to the access
function. The values
are integer constants.
Argument that means, test for read permission.
Argument that means, test for write permission.
Argument that means, test for execute/search permission.
Argument that means, test for existence of the file.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Each file has three timestamps associated with it: its access time,
its modification time, and its attribute modification time. These
correspond to the st_atime
, st_mtime
, and st_ctime
members of the stat
structure; see File Attributes.
All of these times are represented in calendar time format, as
time_t
objects. This data type is defined in ‘time.h’.
For more information about representation and manipulation of time
values, see @ref{Calendar Time}.
When an existing file is opened, its attribute change time and modification time fields are updated. Reading from a file updates its access time attribute, and writing updates its modification time.
When a file is created, all three timestamps for that file are set to the current time. In addition, the attribute change time and modification time fields of the directory that contains the new entry are updated.
Adding a new name for a file with the link
function updates the
attribute change time field of the file being linked, and both the
attribute change time and modification time fields of the directory
containing the new name. These same fields are affected if a file name
is deleted with unlink
, remove
, or rmdir
. Renaming
a file with rename
affects only the attribute change time and
modification time fields of the two parent directories involved, and not
the times for the file being renamed.
Changing attributes of a file (for example, with chmod
) updates
its attribute change time field.
You can also change some of the timestamps of a file explicitly using
the utime
function—all except the attribute change time. You
need to include the header file ‘utime.h’ to use this facility.
The utimbuf
structure is used with the utime
function to
specify new access and modification times for a file. It contains the
following members:
time_t actime
This is the access time for the file.
time_t modtime
This is the modification time for the file.
This function is used to modify the file times associated with the file named filename.
If times is a null pointer, then the access and modification times
of the file are set to the current time. Otherwise, they are set to the
values from the actime
and modtime
members (respectively)
of the utimbuf
structure pointed at by times.
The attribute modification time for the file is set to the current time in either case (since changing the timestamps is itself a modification of the file attributes).
The utime
function returns 0
if successful and -1
on failure. In addition to the usual file name syntax errors
(@pxref{File Name Errors}), the following errno
error conditions
are defined for this function:
EACCES
There is a permission problem in the case where a null pointer was passed as the times argument. In order to update the timestamp on the file, you must either be the owner of the file, have write permission on the file, or be a privileged user.
ENOENT
The file doesn’t exist.
EPERM
If the times argument is not a null pointer, you must either be the owner of the file or be a privileged user. This error is used to report the problem.
EROFS
The file lives on a read-only file system.
Each of the three time stamps has a corresponding microsecond part,
which extends its resolution. These fields are called
st_atime_usec
, st_mtime_usec
, and st_ctime_usec
;
each has a value between 0 and 999,999, which indicates the time in
microseconds. They correspond to the tv_usec
field of a
timeval
structure; see @ref{High-Resolution Calendar}.
The utimes
function is like utime
, but also lets you specify
the fractional part of the file times. The prototype for this function is
in the header file ‘sys/time.h’.
This function sets the file access and modification times for the file
named by filename. The new file access time is specified by
tvp[0]
, and the new modification time by
tvp[1]
. This function comes from BSD.
The return values and error conditions are the same as for the utime
function.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The mknod
function is the primitive for making special files,
such as files that correspond to devices. The GNU library includes
this function for compatibility with BSD.
The prototype for mknod
is declared in ‘sys/stat.h’.
The mknod
function makes a special file with name filename.
The mode specifies the mode of the file, and may include the various
special file bits, such as S_IFCHR
(for a character special file)
or S_IFBLK
(for a block special file). See section Testing the Type of a File.
The dev argument specifies which device the special file refers to. Its exact interpretation depends on the kind of special file being created.
The return value is 0
on success and -1
on error. In addition
to the usual file name syntax errors (@pxref{File Name Errors}), the
following errno
error conditions are defined for this function:
EPERM
The calling process is not privileged. Only the superuser can create special files.
ENOSPC
The directory or file system that would contain the new file is “full” and cannot be extended.
EROFS
The directory containing the new file can’t be modified because it’s on a read-only file system.
EEXIST
There is already a file named filename. If you want to replace this file, you must remove the old file explicitly first.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
If you need to use a temporary file in your program, you can use the
tmpfile
function to open it. Or you can use the tmpnam
function make a name for a temporary file and then open it in the usual
way with fopen
.
The tempnam
function is like tmpnam
but lets you choose
what directory temporary files will go in, and something about what
their file names will look like.
These facilities are declared in the header file ‘stdio.h’.
This function creates a temporary binary file for update mode, as if by
calling fopen
with mode "wb+"
. The file is deleted
automatically when it is closed or when the program terminates. (On
some other ANSI C systems the file may fail to be deleted if the program
terminates abnormally).
This function constructs and returns a file name that is a valid file
name and that does not name any existing file. If the result
argument is a null pointer, the return value is a pointer to an internal
static string, which might be modified by subsequent calls. Otherwise,
the result argument should be a pointer to an array of at least
L_tmpnam
characters, and the result is written into that array.
It is possible for tmpnam
to fail if you call it too many times.
This is because the fixed length of a temporary file name gives room for
only a finite number of different names. If tmpnam
fails, it
returns a null pointer.
The value of this macro is an integer constant expression that represents
the minimum allocation size of a string large enough to hold the
file name generated by the tmpnam
function.
The macro TMP_MAX
is a lower bound for how many temporary names
you can create with tmpnam
. You can rely on being able to call
tmpnam
at least this many times before it might fail saying you
have made too many temporary file names.
With the GNU library, you can create a very large number of temporary
file names—if you actually create the files, you will probably run out
of disk space before you run out of names. Some other systems have a
fixed, small limit on the number of temporary files. The limit is never
less than 25
.
This function generates a unique temporary filename. If prefix is not a null pointer, up to five characters of this string are used as a prefix for the file name.
The directory prefix for the temporary file name is determined by testing each of the following, in sequence. The directory must exist and be writable.
TMPDIR
, if it is defined.
P_tmpdir
macro.
This function is defined for SVID compatibility.
This macro is the name of the default directory for temporary files.
Older Unix systems did not have the functions just described. Instead
they used mktemp
and mkstemp
. Both of these functions
work by modifying a file name template string you pass. The last six
characters of this string must be ‘XXXXXX’. These six ‘X’s
are replaced with six characters which make the whole string a unique
file name. Usually the template string is something like
‘/tmp/prefixXXXXXX’, and each program uses a unique prefix.
Note: Because mktemp
and mkstemp
modify the
template string, you must not pass string constants to them.
String constants are normally in read-only storage, so your program
would crash when mktemp
or mkstemp
tried to modify the
string.
The mktemp
function generates a unique file name by modifying
template as described above. If successful, it returns
template as modified. If mktemp
cannot find a unique file
name, it makes template an empty string and returns that. If
template does not end with ‘XXXXXX’, mktemp
returns a
null pointer.
The mkstemp
function generates a unique file name just as
mktemp
does, but it also opens the file for you with open
(@pxref{Opening and Closing Files}). If successful, it modifies
template in place and returns a file descriptor open on that file
for reading and writing. If mkstemp
cannot create a
uniquely-named file, it makes template an empty string and returns
-1
. If template does not end with ‘XXXXXX’,
mkstemp
returns -1
and does not modify template.
Unlike mktemp
, mkstemp
is actually guaranteed to create a
unique file that cannot possibly clash with any other program trying to
create a temporary file. This is because it works by calling
open
with the O_EXCL
flag bit, which says you want to
always create a new file, and get an error if the file already exists.
[Top] | [Contents] | [Index] | [ ? ] |
This document was generated on January 16, 2023 using texi2html 5.0.
The buttons in the navigation panels have the following meaning:
Button | Name | Go to | From 1.2.3 go to |
---|---|---|---|
[ << ] | FastBack | Beginning of this chapter or previous chapter | 1 |
[ < ] | Back | Previous section in reading order | 1.2.2 |
[ Up ] | Up | Up section | 1.2 |
[ > ] | Forward | Next section in reading order | 1.2.4 |
[ >> ] | FastForward | Next chapter | 2 |
[Top] | Top | Cover (top) of document | |
[Contents] | Contents | Table of contents | |
[Index] | Index | Index | |
[ ? ] | About | About (help) |
where the Example assumes that the current position is at Subsubsection One-Two-Three of a document of the following structure:
This document was generated on January 16, 2023 using texi2html 5.0.